<template>
  <div class="app-container">
    <div class="Search">
      <!--工具条-->
      <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
        <el-form :inline="true" :model="query">
          <el-form-item>
            <el-input v-model="query.params.storeName" placeholder="店铺名称" />
          </el-form-item>
          <el-form-item v-has="'PLATFROM_TENANT_QUERY'">
            <el-cascader ref="tenantTree" placeholder="所属租户" :props="tenantProps" :options="tenantOptions"
              @change="selectTenant" clearable collapse-tags filterable></el-cascader>
          </el-form-item>
          <el-form-item>
            <el-cascader ref="organTree" placeholder="所属组织" :props="props" :options="organOptions" @change="selectOrgan"
              collapse-tags clearable filterable></el-cascader>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="fetchData">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="success" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </div>
    <div class="block">
      <el-table v-loading="listLoading" :data="list" element-loading-text="Loading" border fit highlight-current-row
        @expand-change="expandChange">
        <el-table-column type="expand" align="center" label="" width="30">
          <template slot-scope="scope">
            <el-table v-loading="listLoading" :data="storeAreaList" element-loading-text="Loading" border
              highlight-current-row>
              <el-table-column align="center" label="序号" width="65">
                <template slot-scope="scope">
                  {{ scope.$index }}
                </template>
              </el-table-column>
              <el-table-column label="区域名称" width="110">
                <template slot-scope="scope">
                  {{ scope.row.areaName }}
                </template>
              </el-table-column>
              <el-table-column label="所属组织" width="110" prop="organId" :formatter="translateOrgan" />
              <el-table-column label="关联地址" width="110">
                <template slot-scope="scope">
                  {{ scope.row.addressId }}
                </template>
              </el-table-column>
              <el-table-column label="是否生效" width="110" prop="enable" :formatter="enableFormat" />
              <el-table-column label="标注">
                <template slot-scope="scope">
                  {{ scope.row.remark }}
                </template>
              </el-table-column>
            </el-table>
            <div class="block">
              <el-pagination :current-page="query.storeArea.currentPage" :page-sizes="[10, 20, 30, 40]"
                :page-size="query.storeArea.pageSize" layout="total, sizes, prev, pager, next, jumper"
                :total="query.storeArea.total" @size-change="handleQueryAreaSizeChange"
                @current-change="handleQueryAreaCurrentChange" />
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="序号" width="65">
          <template slot-scope="scope">
            {{ scope.$index }}
          </template>
        </el-table-column>
        <el-table-column label="店铺名称" width="110">
          <template slot-scope="scope">
            {{ scope.row.storeName }}
          </template>
        </el-table-column>
        <el-table-column label="所属组织" width="110" prop="organId" :formatter="translateOrgan" />
        <el-table-column label="纬度" width="110">
          <template slot-scope="scope">
            {{ scope.row.latitude }}
          </template>
        </el-table-column>
        <el-table-column label="经度" width="110">
          <template slot-scope="scope">
            {{ scope.row.longitude }}
          </template>
        </el-table-column>
        <el-table-column label="标注">
          <template slot-scope="scope">
            {{ scope.row.remark }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" align="center" prop="created_at" label="操作">
          <template slot-scope="scope">
            <el-link v-has="'STORE_EDIT'" icon="el-icon-delete" type="warning" style="cursor: pointer;"
              @click="handleEdit(scope.$index, scope.row)">
              修改
            </el-link>
            <el-link v-has="'STORE_REMOVE'" icon="el-icon-delete" type="danger" style="cursor: pointer;"
              @click="handleDelete(scope.$index, scope.row)">
              删除
            </el-link>
            <el-link v-has="'STORE_AREA_EDIT'" icon="el-icon-edit" type="success" style="cursor: pointer;"
              @click="handleStoreAreaEdit(scope.$index, scope.row)">
              块区添加
            </el-link>
            <el-link v-has="'STORE_STORE_GOODS_ADD'" icon="el-icon-edit" type="success" style="cursor: pointer;"
              @click="handleShowGoodsAdd(scope.$index, scope.row)">
              添加商品
            </el-link>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="block">
      <el-pagination :current-page="currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>
    <div class="block">
      <!--弹框-->
      <el-dialog :title="titleMap[dialogStatus]" :visible.sync="dialogFormVisible">
        <el-form :model="form">
          <el-form-item v-if="addForVisible" label="主键">
            <el-input v-model="form.id" disabled placeholder="主键" auto-complete="off" />
          </el-form-item>
          <el-form-item label="店铺名称">
            <el-input v-model="form.storeName" placeholder="店铺名称" auto-complete="off" />
          </el-form-item>
          <el-form-item v-has="'PLATFROM_TENANT_QUERY'" label="所属租户" placeholder="所属租户" required>
            <el-cascader v-model="form.tenantId" ref="tenantTreeForm" placeholder="所属租户" :props="tenantProps"
              :options="tenantOptions" @change="chooseTenantForm" style="width:100%" clearable collapse-tags
              filterable></el-cascader>
          </el-form-item>
          <el-form-item label="所属组织">
            <el-cascader v-model="form.organId" ref="organTreeForm" placeholder="所属组织" :props="props"
              :options="organFormOptions" @change="chooseOrganForm" style="width:100%" collapse-tags
              filterable></el-cascader>
          </el-form-item>
          <el-form-item label="所属商户">
            <el-cascader v-model="form.merchantId" ref="merchantForm" placeholder="所属组织" :props="merchantProps"
              :options="merchantFormOptions" @change="chooseMerchantForm" style="width:100%" collapse-tags
              filterable></el-cascader>
          </el-form-item>
          <el-form-item label="纬度">
            <el-input v-model="form.latitude" placeholder="纬度" auto-complete="off" />
          </el-form-item>
          <el-form-item label="经度">
            <el-input v-model="form.longitude" placeholder="经度" auto-complete="off" />
          </el-form-item>
          <el-form-item label="标注">
            <el-input v-model="form.remark" placeholder="标注" auto-complete="off" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleEditSave">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <div class="block">
      <!--弹框-->
      <el-dialog :title="titleMap[dialogStatus]" :visible.sync="dialogStoreAreaVisible">
        <el-form :model="form">
          <el-form-item v-if="addForVisible" label="">
            <el-input v-model="storeArea.id" auto-complete="off" />
          </el-form-item>
          <el-form-item label="所属店铺">
            <el-input v-model="storeArea.storeId" disabled placeholder="所属店铺" auto-complete="off" />
          </el-form-item>
          <el-form-item v-has="'PLATFROM_TENANT_QUERY'" label="所属租户" placeholder="所属租户" required>
            <el-cascader v-model="storeArea.tenantId" ref="tenantTreeForm" placeholder="所属租户" :props="tenantProps"
              :options="tenantOptions" @change="chooseTenantForm" style="width:100%" clearable collapse-tags
              filterable></el-cascader>
          </el-form-item>
          <el-form-item label="所属组织">
            <el-cascader v-model="storeArea.organId" ref="organTreeForm" placeholder="所属组织" :props="props"
              :options="organFormOptions" @change="chooseOrganForm" style="width:100%" collapse-tags
              filterable></el-cascader>
          </el-form-item>
          <el-form-item label="区域名称">
            <el-input v-model="storeArea.areaName" placeholder="区域名称" auto-complete="off" />
          </el-form-item>
          <el-form-item label="关联地址">
            <el-input v-model="storeArea.addressId" placeholder="关联地址" auto-complete="off" />
          </el-form-item>
          <el-form-item label="是否生效">
            <el-select v-model="storeArea.enable" style="width:100%" placeholder="是否生效">
              <el-option v-for="item in query.options" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="所属父区域">
            <el-input v-model="storeArea.parentId" placeholder="所属父区域" auto-complete="off" />
          </el-form-item>
          <el-form-item label="标注">
            <el-input v-model="storeArea.remark" placeholder="标注" auto-complete="off" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogStoreAreaVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleStoreAreaSave">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <div class="block">
      <!--弹框-->
      <el-dialog :title="titleMap[dialogStatus]" width="88%" :visible.sync="dialogShowGoodsPriceListAddVisible">
        <div class="block">
          <el-table ref="selectGoodsTable" v-loading="listLoading" :data="goodsPriceList" element-loading-text="Loading"
            border fit row-key="id" @selection-change="handleGoodsPriceSelectionChange" highlight-current-row>
            <el-table-column type="selection" width="40" />
            <el-table-column align="center" label="序号" width="40">
              <template slot-scope="scope">
                {{ scope.$index }}
              </template>
            </el-table-column>
            <el-table-column label="关联商品" width="110">
              <template slot-scope="scope">
                {{ scope.row.goodsId }}
              </template>
            </el-table-column>
            <el-table-column label="商品图片url" width="110">
              <template slot-scope="scope">
                <el-image style="width: 100px; height: 100px" :src="scope.row.goods.goodsImg">
                </el-image>
              </template>
            </el-table-column>
            <el-table-column label="商品名称" width="110">
              <template slot-scope="scope">
                {{ scope.row.goodsName }}
              </template>
            </el-table-column>
            <el-table-column label="价格(单位：分)" width="110">
              <template slot-scope="scope">
                {{ scope.row.price }}
              </template>
            </el-table-column>
            <el-table-column label="商品成本(单位：分)" width="110">
              <template slot-scope="scope">
                {{ scope.row.costPrice }}
              </template>
            </el-table-column>
            <el-table-column label="折扣价格(单位：分)" width="110">
              <template slot-scope="scope">
                {{ scope.row.discountPrice }}
              </template>
            </el-table-column>
            <el-table-column label="建议价格(单位：分)" width="110">
              <template slot-scope="scope">
                {{ scope.row.suggestedRetailPrice }}
              </template>
            </el-table-column>
            <el-table-column label="商品编码" width="110">
              <template slot-scope="scope">
                {{ scope.row.goodsCode }}
              </template>
            </el-table-column>
            <el-table-column label="所属组织" width="110">
              <template slot-scope="scope">
                {{ scope.row.organId }}
              </template>
            </el-table-column>
            <el-table-column label="组织路径" width="110">
              <template slot-scope="scope">
                {{ scope.row.organPath }}
              </template>
            </el-table-column>
            <el-table-column label="备注" width="110">
              <template slot-scope="scope">
                {{ scope.row.remark }}
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="block">
          <el-pagination :current-page="query.goods.currentPage" :page-sizes="[10, 20, 30, 40]"
            :page-size="query.goods.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="query.goods.total"
            @size-change="handleGoodsPriceSizeChange" @current-change="handleGoodsPriceCurrentChange" />
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogShowGoodsPriceListAddVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleGoodsImgEditSave">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import { getList, doDelete, doEdit } from '@/api/Store/'
import { getList as getStoreAreaList, doDelete as doDeleteStoreArea, doEdit as doStoreAreaEdit } from '@/api/StoreArea/'
import { getList as queryGoodsPagination } from '@/api/goods'
import { queryGoodsPriceBy as getGoodsPrice, getList as getGoodsPriceList } from '@/api/goodsPrice'
import { batchSave as batchSaveStoreGoods, queryAssignedGoods } from '@/api/StoreGoods/'
import { getList as queryMerchantPage } from '@/api/Merchant/'


import { getOrganId, getTenantId, getOrganPath, getCurrentLoginUserId, handleBuildTreeDataStruct, getSuperManagerId, getSelectedNodes, getSelectedNodesObject, getSystemErrorCode, getCurrentTimeYYYY_MM_dd_HH_mm_ss } from '@/api/utils'
import { getTenantList, getOrganList, getDictionary, translateOrganId2OrganName } from '@/utils/auth'
import localStorageUtil from '@/utils/localStorageUtil'
import { getDictionaryGroup } from '@/api/dictionary'
import { getList as getOrganPager, querySubordinateOrgan, queryAssigneeOrgan } from '@/api/Organ'


export default {
  data() {
    return {
      list: [],
      listLoading: true,
      total: 5,
      currentPage: 1,
      pageSize: 10,
      dialogFormVisible: false,
      addForVisible: false,
      dialogStoreAreaVisible: false,
      goodsPriceList: [],
      storeAreaList: [],
      dialogShowGoodsPriceListAddVisible: false,
      storeGoodsList: [],
      organTree: [],
      form: {
        addressId: '',
        createBy: '',
        createDate: '',
        enable: '',
        id: '',
        latitude: '',
        longitude: '',
        organId: '',
        organPath: '',
        remark: '',
        storeName: '',
        updateBy: '',
        updateDate: ''
      },
      storeArea: {
        addressId: '',
        areaName: '',
        createBy: '',
        createDate: '',
        enable: '',
        id: '',
        organId: '',
        organPath: '',
        parentId: '',
        remark: '',
        sorted: '',
        storeId: '',
        updateBy: '',
        updateDate: ''
      },

      // 新增or编辑弹框标题(根据点击的新增or编辑按钮显示不同的标题)
      titleMap: {
        add: '新增',
        edit: '编辑',
        addGoods: '添加商品',
        addStoreArea: '添加商铺块区'
      },
      props: { // 配置项（必选）
        value: 'id',
        label: 'organName',
        children: 'children',
        title: '组织',
        multiple: false,
        checkStrictly: true,
        emitPath: false
        // disabled:true
      },
      merchantProps: {
        value: 'id',
        children: 'children',
        label: 'name',
        url: 'url',
        multiple: false,
        checkStrictly: true,
        emitPath: false
      },
      organTreeProps: {
        children: 'children',
        label: 'organName',
        url: 'url'
      },
      tenantProps: { // 配置项（必选）
        value: 'id',
        label: 'organName',
        children: 'children',
        title: '租户',
        multiple: false,
        checkStrictly: true,
        emitPath: false
        // disabled:true
      },
      organFormOptions: [],
      merchantFormOptions: [],
      tenantOptions: [],
      organOptions: [{ id: '1', parentId: '2', organName: '平台', children: [] }],
      // 新增和编辑弹框标题
      dialogStatus: '',
      query: {
        params: {
          organIds: [],
          addressId: '', // 关联地址
          createBy: '', // 添加者
          createDate: '', // 新增时间
          enable: '', // 是否生效
          id: '', // 主键,
          tenantId: '',
          latitude: '', // 纬度
          longitude: '', // 经度
          organId: '', // 所属组织
          organPath: '', // 组织路径
          remark: '', // 标注
          storeName: '', // 店铺名称
          updateBy: '', // 更新者
          updateDate: '' // 更新时间

        },
        goods: {
          assignee: {
            id: '',
            organPath: ''
          },
          total: 10,
          currentPage: 1,
          pageSize: 10
        },
        storeArea: {
          addressId: '',
          areaName: '',
          createBy: '',
          createDate: '',
          enable: '',
          id: '',
          organId: '',
          organPath: '',
          parentId: '',
          remark: '',
          sorted: '',
          storeId: '',
          updateBy: '',
          updateDate: '',
          total: 0,
          currentPage: 1,
          pageSize: 10
        },
        storeGoods: {
          storeId: '',
          organId: '',
          tenantId: ''
        },
        merchant: {
          name: '',
          type: '',
          organId: '',
          organPath: '',
          isMain: '',
          cooperationMode: '',
          userId: '',
          ifCheckUser: true,
          ifCheckIsMain: true,
          profitSharingRate: '',
          total: 10,
          currentPage: 1,
          pageSize: 10
        },
        timeValue: '',
        options: [{
          value: '1',
          label: '黄金糕'
        }, {
          value: '2',
          label: '双皮奶'
        }, {
          value: '3',
          label: '蚵仔煎'
        }, {
          value: '4',
          label: '龙须面'
        }, {
          value: '5',
          label: '北京烤鸭'
        }],
        enableOptions: [{
          value: '0',
          label: '失效'
        }, {
          value: '1',
          label: '生效'
        }],
        value: ''
      }
    }
  },
  created() {
    this.initOrganTree(() => {
      this.setOrganQueryType()
    }, getOrganPath())
    this.initOrganFormTree()
    this.handleFiltTenant()
    this.handleBuildEnableOptions()
    this.handleQueryMerchant()
    this.fetchData()
  },
  methods: {
    translateOrgan(row) {
      return translateOrganId2OrganName(row);
    },
    enableFormat(row, column) {

      let label = ''
      for (let i = 0; i < this.query.enableOptions.length; i++) {
        if ('' + row.enable === this.query.enableOptions[i].value) {
          return this.query.enableOptions[i].label
        }
      }
      return label
    },
    fetchData() {
      this.createOrganQuery()
      this.currentPage = this.currentPage || 1
      this.pageSize = this.pageSize || 10
      this.listLoading = true
      getList(this.query.params, this.currentPage, this.pageSize).then(response => {
        const data = response.data
        if (!data.entities || typeof data.successful != 'undefined') {
          this.$message({
            type: 'info',
            message: data.description || getSystemErrorCode(data.status)
          })
        }
        this.total = data.totalCount
        this.pageSize = data.pageSize
        this.currentPage = data.currentPage
        this.list = data.entities
        this.listLoading = false
      })
    },
    createOrganQuery() {
      // 选中了租户
      let tenantSelected = this.$refs['tenantTree'] && this.$refs['tenantTree'].getCheckedNodes() || []
      let organSelected = this.$refs['organTree'] && this.$refs['organTree'].getCheckedNodes() || []
      let that = this
      this.query.params.organId = null
      if (tenantSelected.length && tenantSelected[0]) {
        this.query.params.tenantId = tenantSelected[0].data.id
        if (organSelected.length && organSelected[0]) {
          if (this.props.multiple) {
            this.query.params.organId = null
            this.query.params.organIds = []
            if (organSelected.length && organSelected[0]) {
              organSelected.forEach(function (element) {
                that.query.params.organIds.push(element.data.id)
              })
            }
          } else if (organSelected.length && organSelected[0]) {
            this.query.params.organPath = organSelected[0] && organSelected[0].data.organPath
          }
        }
      } else {
        this.query.params.tenantId = getTenantId()
        if (organSelected.length && organSelected[0]) {
          if (this.props.multiple) {
            this.query.params.organId = null
            this.query.params.organIds = []
            if (organSelected.length && organSelected[0]) {
              organSelected.forEach(function (element) {
                that.query.params.organIds.push(element.data.id)
              })
            }
          } else if (organSelected.length && organSelected[0]) {
            this.query.params.organPath = organSelected[0].data.organPath
          }
        }

      }
      this.query.params.organId = this.query.params.organId || getOrganId()
      this.query.params.organPath = this.query.params.organPath || getOrganPath()
    },
    handleSizeChange(val) {
      this.currentPage = 1
      this.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    },
    // 新增
    handleAdd() {
      // 显示弹框
      this.dialogFormVisible = true
      // 新增弹框标题
      this.dialogStatus = 'add'

      this.form.addressId = ''
      this.form.createBy = getCurrentLoginUserId()
      this.form.createDate = ''
      this.form.enable = ''
      this.form.id = ''
      this.form.latitude = ''
      this.form.longitude = ''
      this.form.organId = getOrganId()
      this.form.tenantId = getTenantId()
      this.form.organPath = getOrganPath()
      this.form.remark = ''
      this.form.storeName = ''
      this.form.updateBy = getCurrentLoginUserId()
      this.form.updateDate = ''
      this.addForVisible = false
    },
    // 编辑
    handleEdit(index, row) {
      console.log(index)
      console.log(row)

      this.form.addressId = row.addressId
      this.form.createBy = row.createBy
      this.form.createDate = row.createDate
      this.form.enable = row.enable
      this.form.id = row.id
      this.form.latitude = row.latitude
      this.form.longitude = row.longitude
      this.form.organId = row.organId
      this.form.organPath = row.organPath
      this.form.remark = row.remark
      this.form.storeName = row.storeName
      this.form.updateBy = getCurrentLoginUserId()
      this.form.updateDate = row.updateDate
      this.form.tenantId = getTenantId()

      this.addForVisible = true

      // 显示弹框
      this.dialogFormVisible = true
      // 编辑弹框标题
      this.dialogStatus = 'edit'
    },
    handleStoreAreaEdit(index, row) {
      // 显示弹框
      this.dialogStoreAreaVisible = true
      // 新增弹框标题
      this.dialogStatus = 'addStoreArea'

      this.storeArea.addressId = ''
      this.storeArea.areaName = ''
      this.storeArea.createBy = getCurrentLoginUserId()
      this.storeArea.createDate = ''
      this.storeArea.enable = ''
      this.storeArea.id = ''
      this.storeArea.organId = row.organId || getOrganId()
      this.storeArea.tenantId = row.tenantId || getTenantId()
      this.storeArea.organPath = ''
      this.storeArea.parentId = ''
      this.storeArea.remark = ''
      this.storeArea.sorted = ''
      this.storeArea.storeId = row.id
      this.storeArea.updateBy = getCurrentLoginUserId()
      this.storeArea.updateDate = ''
      this.addForVisible = false
    },
    handleStoreGoodsEdit(index, row) {
      // 显示弹框
      this.dialogStoreAreaVisible = true
      // 新增弹框标题
      this.dialogStatus = 'add'

      this.storeArea.addressId = ''
      this.storeArea.areaName = ''
      this.storeArea.createBy = getCurrentLoginUserId()
      this.storeArea.createDate = ''
      this.storeArea.enable = ''
      this.storeArea.id = ''
      this.storeArea.organId = getOrganId()
      this.storeArea.organPath = getOrganPath()
      this.storeArea.parentId = ''
      this.storeArea.remark = ''
      this.storeArea.sorted = ''
      this.storeArea.storeId = row.id
      this.storeArea.updateBy = getCurrentLoginUserId()
      this.storeArea.updateDate = ''
      this.addForVisible = false
    },
    handleDelete(index, row) {
      console.log(index)
      console.log(row)

      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        doDelete(row.id).then(response => {
          const data = response.data
          console.log(data)
          if (data.status === 1) {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.fetchData()
          } else if (data.status === 403) {
            this.$message({
              type: 'warning',
              message: data.description
            })
          } else {
            this.$message({
              type: 'info',
              message: '操作失败!'
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleEditSave() {

      this.form.organId = this.form.organId || getOrganId();
      this.form.organPath = this.form.organPath || getOrganPath();
      this.form.tenantId = this.form.tenantId || getTenantId();
      doEdit(this.form).then(response => {

        const data = response.data
        if (data.status) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.fetchData()
        } else {
          this.$message({
            type: 'info',
            message: '操作失败!'
          })
        }
        this.listLoading = false
        this.dialogFormVisible = false
      })
    },
    handleStoreAreaSave() {

      this.storeArea.organId = this.storeArea.organId || getOrganId()
      this.storeArea.organPath = this.storeArea.organPath || getOrganPath()
      this.storeArea.tenantId = this.storeArea.tenantId || getTenantId();
      doStoreAreaEdit(this.storeArea).then(response => {

        const data = response.data
        if (data.successful) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
        } else {
          this.$message({
            type: 'info',
            message: '操作失败!'
          })
        }
        this.listLoading = false
        this.dialogFormVisible = false
      })
    },
    handleReset() {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    initOrganTree(fn, filter, that) {
      this.listLoading = true
      let data = getOrganList()
      if (filter) {
        data = data.filter(function (item, index) {
          return item.organPath.indexOf(filter) >= 0
        })
      }
      if (that && that.organFormOptions && that.organFormOptions.length >= 0) {
        that.organFormOptions = handleBuildTreeDataStruct(data, 'id', 'parentId')
      } else {
        this.organOptions = handleBuildTreeDataStruct(data, 'id', 'parentId')
      }
      this.listLoading = false
      if (fn) {
        fn()
      }
    },
    initOrganFormTree(fn, filter) {
      this.initOrganTree(fn, filter, this)
    },
    setOrganQueryType() {
      this.organQueryModelChange(localStorageUtil.fetch("SYSTEM_SETTING_ORGAN_QUERY_MODEL"))
    },
    selectOrgan(nodes) {
      let nodesInfo = this.$refs['organTree'].getCheckedNodes()
      let that = this
      this.query.params.organPath = ''
      this.query.params.organIds = []
      if (this.props.multiple) {
        this.query.params.organIds = []
        if (nodesInfo.length) {
          nodesInfo.forEach(function (element) {
            that.query.params.organIds.push(element.data.id)
          })
        }
      } else if (nodesInfo.length) {
        this.query.params.organPath = nodesInfo[0].data.organPath
      }
    },
    selectTenant(nodes) {
      let nodesInfo = this.$refs['tenantTree'].getCheckedNodes()
      let that = this
      this.query.params.tenantId = ''
      this.query.params.tenantIds = []
      this.query.params.organId = null
      this.query.params.organIds = []
      this.query.params.organPath = null

      if (this.tenantProps.multiple) {
        this.query.params.tenantIds = []
        if (nodesInfo.length) {
          nodesInfo.forEach(function (element) {
            that.query.params.tenantIds.push(element.data.id)
          })
        }
      } else if (nodesInfo.length) {
        this.query.params.tenantId = nodesInfo[0].data.id
        this.initOrganTree(function () {
          that.setOrganQueryType()
        }, nodesInfo[0].data.organPath)
      } else {
        this.initOrganTree(function () {
          that.setOrganQueryType()
        })
      }
    },
    chooseTenantForm(nodes) {
      let nodesInfo = this.$refs['tenantTreeForm'].getCheckedNodes()
      this.form.tenantId = null
      let that = this
      debugger
      if (nodesInfo.length) {
        this.form.tenantId = nodesInfo[0].data.id
        this.initOrganFormTree(function () {
          that.setOrganQueryType()
        }, nodesInfo[0].data.organPath, this.organFormOptions)
      } else {
        this.initOrganFormTree(function () {
          that.setOrganQueryType()
        }, null, this.organFormOptions)
      }
    },
    organQueryModelChange(organQueryModel) {
      if (organQueryModel == 'selected') {
        this.props.multiple = true
      } else if (organQueryModel == 'selfAndSub') {
        this.props.multiple = false
      }
    },
    chooseOrganForm(nodes) {
      let nodesInfo = this.$refs['organTreeForm'].getCheckedNodes()
      if (nodesInfo[0]) {
        this.form.organPath = nodesInfo[0].data.organPath
        this.form.organId = nodesInfo[0].data.id
        this.form.tenantId = nodesInfo[0].data.tenantId
      }
    },
    handleFiltTenant() {
      let data = getOrganList()
      this.tenantOptions = data.filter(function (item, index) {
        return item.type == 0 || item.type == 1;
      })
    },
    handleShowGoodsAdd(index, row) {
      this.dialogStatus = 'addGoods'
      this.dialogShowGoodsPriceListAddVisible = true
      this.query.storeGoods.storeId = row.id

      this.query.storeGoods.organId = row.organId || getOrganId()
      this.query.storeGoods.organPath = row.organPath || getOrganPath()
      this.query.storeGoods.tenantId = row.tenantId || getTenantId()

      this.showGoods()
    },
    handleGoodsPriceSizeChange(val) {
      this.query.goods.pageSize = val
      this.query.goods.currentPage = 1
      this.showGoods()
    },
    handleGoodsPriceCurrentChange(val) {
      this.query.goods.currentPage = val
      this.showGoods()
    },
    showGoods() {
      this.dialogSelectGoodsFormVisible = true
      this.query.goods.organId = this.query.storeGoods.organId
      this.query.goods.tenantId = this.query.storeGoods.tenantId
      this.query.goods.organPath = this.query.storeGoods.organPath

      //this.query.goods.assignee.organPath = getOrganPath()
      getGoodsPriceList(this.query.goods, this.query.goods.currentPage, this.query.goods.pageSize).then(response => {
        const data = response.data
        if (!data.entities || typeof data.successful != 'undefined') {
          this.$message({
            type: 'info',
            message: data.description || getSystemErrorCode(data.status)
          })
          return
        }
        this.query.goods.total = data.totalCount
        this.query.goods.pageSize = data.pageSize
        this.query.goods.currentPage = data.currentPage
        this.goodsPriceList = data.entities
        this.handleSelectedGoods(this.goodsPriceList)
        this.listLoading = false
      })
    },
    handleSelectedGoods(goodsPriceList) {
      let storeGoods = {
        storeId: this.query.storeGoods.storeId,
        organId: this.query.storeGoods.organId,
        tenantId: this.query.storeGoods.tenantId,
        goodsVOs: []
      }
      debugger
      let goodsVOs = []
      let selectedOrigin = {}
      if (goodsPriceList && goodsPriceList.length) {
        goodsPriceList.forEach(goodsPrice => {
          goodsVOs.push({ id: goodsPrice.goodsId })
          selectedOrigin[goodsPrice.id] = goodsPrice
        })

        storeGoods.goodsVOs = goodsVOs
        queryAssignedGoods(storeGoods).then(response => {
          const gateway = response.data
          let selectedGoods = gateway.data
          this.$nextTick(function () {
            selectedGoods.forEach(row => {
              this.$refs.selectGoodsTable.toggleRowSelection(selectedOrigin[row.goodsPriceId]);
            })
          })
          this.listLoading = false
        })

      }

    },
    expandChange(row, rowExtended) {

      if (!rowExtended) {
        return;
      }
      this.query.storeArea.storeId = row.id
      this.listLoading = true
      this.query.storeArea.tenantId = row.tenantId || getTenantId()
      this.query.storeArea.organId = row.organId || getOrganId()
      this.query.storeArea.organPath = row.organPath || getOrganPath()

      getStoreAreaList(this.query.storeArea, this.query.storeArea.currentPage, this.query.storeArea.pageSize).then(response => {
        const data = response.data
        if (!data.entities || typeof data.successful != 'undefined') {
          this.$message({
            type: 'info',
            message: data.description || getSystemErrorCode(data.status)
          })
          return
        } else {
          this.query.storeArea.total = data.totalCount
          this.query.storeArea.pageSize = data.pageSize
          this.query.storeArea.currentPage = data.currentPage
          this.storeAreaList = data.entities
        }
        this.listLoading = false
      })

      // this.handleQueryGoodsTypeSpecificationItem()
    },
    handleGoodsPriceSelectionChange(selectedNodes) {
      if (selectedNodes.length) {
        this.storeGoodsList = []
        for (var i = 0; i < selectedNodes.length; i++) {
          let node = selectedNodes[i]
          let storeGoods = {
            remark: '',
            organId: getOrganId(),
            organPath: getOrganPath(),
            tenantId: getTenantId(),
            isDeleted: '',
            storeId: this.query.storeGoods.storeId,
            goodsId: node.goodsId,
            goodsPriceId: node.id,
            goodsTypeId: node.goodsTypeId,
            goodsTypePath: node.goodsTypePath,
            goodsImg: node.goods.goodsImg,
            goodsName: node.goodsName,
            goodsPrice: node.price,
            discountPrice: node.discountPrice,
            isHot: '',
            costPrice: node.costPrice,
            suggestedRetailPrice: node.suggestedRetailPrice,
            createBy: getCurrentLoginUserId(),
            updateBy: getCurrentLoginUserId()
          }
          this.storeGoodsList.push(storeGoods)
        }
      }
    },
    handleGoodsImgEditSave() {
      if (!this.storeGoodsList.length) {
        this.$message({
          type: 'warning',
          message: '请选择需求添加到商铺的商品!'
        })
        return;
      }
      batchSaveStoreGoods(this.storeGoodsList).then(response => {
        console.log(response)
        const data = response.data
        if (data.status) {
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
          this.fetchData()
        } else {
          this.$message({
            type: 'info',
            message: '操作失败!'
          })
        }
      })

    },
    handleBuildEnableOptions() {

      const datas = getDictionary()
      let data = datas.filter(function (item, index) {
        return item.bigType === "UserEnable" && item.parentId != '0';
      })
      let enableOptions = [];
      for (let i = 0; i < data.length; i++) {

        let option = {}
        option['value'] = data[i].value
        option['label'] = data[i].desc
        enableOptions.push(option)
      }
      this.query.enableOptions = enableOptions
    },
    handleQueryAreaSizeChange() {

    },
    handleQueryAreaCurrentChange() {

    },
    handleQueryMerchant() {

      this.query.merchant.organId = getOrganId()
      this.query.merchant.organPath = getOrganPath()
      this.query.merchant.tenantId = getTenantId()
      this.query.merchant.pageSize = this.query.merchant.pageSize || 10
      this.query.merchant.currentPage = this.query.merchant.currentPage || 1

      queryMerchantPage(this.query.merchant, this.query.merchant.currentPage, this.query.merchant.pageSize).then(response => {

        const data = response.data
        this.query.merchant.total = data.totalCount
        this.query.merchant.pageSize = data.pageSize
        this.query.merchant.currentPage = data.currentPage
        this.merchantFormOptions = handleBuildTreeDataStruct(data.entities, 'id', 'parentId')
        this.listLoading = false
      })

    },
    chooseMerchantForm() {
      let nodesInfo = this.$refs['merchantForm'].getCheckedNodes()
      if (nodesInfo[0]) {
        this.form.merchantId = nodesInfo[0].data.id
        this.form.merchantName = nodesInfo[0].data.merchantName
      }
    }
  }
}

</script>
